package com.jy.rhin.infra.repo.notfication.publish.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jy.rhin.infra.repo.notfication.publish.po.PublishMessageStatisticsPO;
import com.jy.rhin.sdk.dto.notification.resp.CountDateNotificationRespDto;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: lww
 * @Date: 2022/11/16 9:57
 */
public interface PublishMessageStatisticsMapper extends BaseMapper<PublishMessageStatisticsPO> {

    /**
     * 删除对应时间段的消息通知数据
     *
     * @param startDate
     * @param endDate
     */
    @Delete(" DELETE FROM t_notification_log_statistics                           \n" +
            " WHERE notify_date BETWEEN DATE_FORMAT(#{startDate},'%Y-%m-%d')      \n" +
            " AND DATE_FORMAT(#{endDate},'%Y-%m-%d')")
    void deleteStatistics(@Param("startDate") Date startDate, @Param("endDate") Date endDate);

    /**
     * 补充对应时间段的消息通知数据
     *
     * @param startDate
     * @param endDate
     */
    @Select(" INSERT INTO t_notification_log_statistics(id,notify_date,total)                                           \n" +
            " SELECT UUID_SHORT() AS id, date(notify_time) AS notifyDate, count(1) AS total FROM t_notification_log     \n" +
            " WHERE notify_time >= DATE_FORMAT(#{startDate},'%Y-%m-%d %H:%i:%s')                                        \n" +
            " AND notify_time < DATE_FORMAT(#{endDate},'%Y-%m-%d %H:%i:%s') AND notify_status = 'DONE'                  \n" +
            " GROUP BY notifyDate ORDER BY notifyDate DESC ")
    void insertStatistics(@Param("startDate") Date startDate, @Param("endDate") Date endDate);

    /**
     * 查询对应时间段的消息通知数据
     *
     * @param startDate
     * @param endDate
     * @return
     */
    @Select(" SELECT notify_date as notifyDate, total FROM t_notification_log_statistics                      \n" +
            " WHERE notify_date BETWEEN DATE_FORMAT(#{startDate},'%Y-%m-%d')                                  \n" +
            " AND DATE_FORMAT(#{endDate},'%Y-%m-%d') ORDER BY notify_date DESC ")
    List<CountDateNotificationRespDto> queryStatistics(@Param("startDate") Date startDate, @Param("endDate") Date endDate);

    /**
     * 根据日期查询是否存在该记录
     * @param notifyDate
     * @return
     */
    @Select("SELECT count(1) FROM t_notification_log_statistics WHERE notify_date = DATE_FORMAT(#{notifyDate},'%Y-%m-%d')")
    Integer countByNotifyDate(@Param("notifyDate") Date notifyDate);

    /**
     * 根据日期更新消息通知数量
     *
     * @param total
     * @param notifyDate
     */
    @Select("UPDATE t_notification_log_statistics SET total= #{total} WHERE notify_date = DATE_FORMAT(#{notifyDate},'%Y-%m-%d') ")
    void updateTotalByNotifyDate(@Param("total") Integer total, @Param("notifyDate") Date notifyDate);

}
